package org.muninn.niagara.services;

import java.math.BigInteger;

import javax.baja.sys.BObject;
import javax.baja.sys.Sys;
import javax.baja.sys.Type;

public class Bob extends BObject
{
  public static boolean testLic(String strang)
  {
    long[] ciphers = hash();
    long[] codes = decryptAndTest(strang);
    
    boolean match = true;
    for (int i = 0; i < codes.length; i++)
      match = match && (ciphers[i] == codes[i]);
    
    return match;
  }
  
  public static long[] decryptAndTest(String code)
  {
    String[] codeStrings = new String[3];
    long[] codeInts = new long[4];
    codeStrings = code.split("-");
    
    if (codeStrings.length != 4)
      return null;
    
    for (int i = 0; i < codeStrings.length; i++)
      codeInts[i] = BigInteger.valueOf((long) Integer.parseInt(codeStrings[i], 36)).modPow(BigInteger.valueOf(4411), BigInteger.valueOf(47154089)).longValue();
    
    return codeInts;
  }
  
  public static long[] hash()
  {
    long[] hashes = new long[4];
    String[] bits = Sys.getHostId().split("-");
    
    for (int i = 0, k = 0; i < bits.length; i++)
    {
      long hash = 7;
      
      if (bits[i].length() == 5)
        bits[i] = bits[i].substring(1);
      
      if (bits[i].length() == 4)
      {
        for (int j = 0; j < bits[i].length(); j++)
          hash = hash * 43 + bits[i].charAt(j);
        
        hashes[k] = hash;
        k++;
      }
    }
    
    return hashes;
  }
  
  public static boolean testLic(BMuninnServiceContainer comp) { return testLic(comp.getLicenseCode()); }
  
  public static final Type TYPE = Sys.loadType(Bob.class);
  public Type getType() { return TYPE; }
}
